package vn.cuhanh;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.cuhanh.bean.Account;
import vn.cuhanh.bean.Game;
import vn.cuhanh.utils.CuhanhDao;
import vn.cuhanh.utils.HelperFunc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
	
	public static String username = null;
	public static int userId = 160239352;
	public static boolean isLogin = false;
	public static String sessionId = "";
	public static Account userAccount = null;
	public static boolean useGoogleAnalytic = true;
	private Handler handler = new Handler();
	private static Thread threadLoadGames = null;
	public static String deviceImei = ""; 
	public static String versionName;
	public static int versionCode;
	private Timer timer;
	
	private boolean waitingTimeout = false;
	private boolean gameInfoLoaded = false;
	private boolean checkUserLoginStatusFinished = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getAppInfo();
		setContentView(R.layout.home);
		threadLoadGames = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				final String response = HelperFunc.getDataFromSv("http://staging.choapp.vn/mg/test");
				Log.d("response", "message: " + response);
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
//						String message = "";
						try {
							JSONArray jsonGames = new JSONArray(response);
							ArrayList<Game> games = new ArrayList<Game>();
							for (int i = 0; i < jsonGames.length(); i++) {
								JSONObject o = jsonGames.getJSONObject(i);
								Game game = new Game(o.getInt("id"), o.getString("appName"), o.getString("image"), o.getString("image"));
								JSONArray jsonPages = o.getJSONArray("features");
								int[] pages = new int[jsonPages.length()];
								for (int j = 0; j < jsonPages.length(); j++) {
									pages[j] = jsonPages.getInt(j);
								}
								game.setPages(pages);
								games.add(game);
							}
							ChooseGameActivity.games = games;
							gameInfoLoaded = true;
							startChooseGame();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});
			}
		});
		loadGames();
		checkUserLogin();
		checkFolders();
	}
	
	public void getAppInfo() {
		getDeviceImei();
		try {
			PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			versionName = pInfo.versionName;
			versionCode = pInfo.versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void checkUserLogin() {
		doCheckUserLogin(this);
		Log.d("mainActivity", "is login: " + String.valueOf(MainActivity.isLogin));
		checkUserLoginStatusFinished = true;
		startChooseGame();
	}
	
	public static void doCheckUserLogin(Context ctx) {
		MainActivity.userAccount = CuhanhDao.getAccount(ctx);
		if(userAccount != null) {
			userId = userAccount.getId();
			username = userAccount.getUserName();
			MainActivity.isLogin = true;
		} else {
			MainActivity.isLogin = false;
		}
	}
	
	public void startChooseGame() {
		if(!waitingTimeout || !gameInfoLoaded || !checkUserLoginStatusFinished) {
			return;
		}
		timer.cancel();
		if(ChooseGameActivity.games != null && ChooseGameActivity.games.size() == 1) {
			ChooseGameActivity.current = ChooseGameActivity.games.get(0);
			ChooseGameActivity.goToGameDetail(this, ChooseGameActivity.games.get(0));
			return;
		}
		Intent intentChooseGame = new Intent(MainActivity.this, ChooseGameActivity.class);
		startActivity(intentChooseGame);
	}
	
	private String getDeviceImei() {
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

		deviceImei = telephonyManager.getDeviceId(); 

		if (deviceImei == null) { 

		deviceImei = Settings.Secure.getString(getContentResolver(), 

		Settings.Secure.ANDROID_ID); 

		}

		return deviceImei;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void loadGames() {
		try {
			ChooseGameActivity.games = HelperFunc.getListGame(this);
			if(ChooseGameActivity.games != null) {
				gameInfoLoaded = true;
				Log.d("cuhanh", "don't need network");
				startChooseGame();
				return;
			}
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
		threadLoadGames.start();
	}
	
	public void checkFolders() {
		try {
			File SDCardRoot = Environment.getExternalStorageDirectory();
			File appRoot = new File(SDCardRoot, getResources().getString(R.string.localRootFolder));
			if(!appRoot.exists()) {
				appRoot.mkdirs();
			}
			File apkFolder = new File(SDCardRoot, getResources().getString(R.string.update_apk_folder));
			if(!apkFolder.exists()) {
				apkFolder.mkdirs();
			}
			File imagesFolder = new File(SDCardRoot, getResources().getString(R.string.images_folder));
			if(!imagesFolder.exists()) {
				imagesFolder.mkdirs();
			}
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
	}
	
	@Override
	public void onResume(){
		super.onResume();

		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				waitingTimeout = true;
				startChooseGame();
			}
		}, 2000, 2000);
	}
}
